package com.cheung.leetcode.tree;

import lyroot.entity.TreeNode;
import org.junit.jupiter.api.Test;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @BelongsProject : java-leetcode
 * @BelongsPackage : com.cheung.leetcode.tree
 * @Author :  cheungming
 * @CreateTime : 2024-05-15 10:54:21
 * @Description : 二叉树的先序（前序）遍历
 * @Version : 1.0
 */
public class Code144Test {

    public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        search(root, result);
        return result;
    }


    public void search(TreeNode node, List<Integer> result) {
        if (node == null) {
            return;
        }
        result.add(node.val);
        // 前序遍历，根左右
        search(node.left, result);
        search(node.right, result);
    }


    @Test
    public void test1() {
        TreeNode root = new TreeNode(1);

        TreeNode node2 = new TreeNode(2);
        root.right = node2;

        node2.left = new TreeNode(3);


        List<Integer> list = List.of(1, 2, 3);
        assert Objects.equals(list, preorderTraversal(root));
    }


    @Test
    public void test2() {
        List<Integer> list = List.of();
        assert Objects.equals(list, preorderTraversal(null));
    }

    @Test
    public void test3() {
        TreeNode root = new TreeNode(1);
        root.left = new TreeNode(2);

        List<Integer> list = List.of(1, 2);
        assert Objects.equals(list, preorderTraversal(root));
    }

    @Test
    public void test4() {
        TreeNode root = new TreeNode(1);
        root.right = new TreeNode(2);

        List<Integer> list = List.of(1, 2);
        assert Objects.equals(list, preorderTraversal(root));
    }

}
